<template>
  <ContentWrap class="mobile-container">
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="auto">
      <el-form-item :label="t('common.id')">
        <el-input
          v-model="form.id"
          :clearable="true"
          :placeholder="t('common.inputText') + t('common.id')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('order.customer')">
        <el-select
          v-model="form.user_id"
          :placeholder="t('common.inputText') + t('order.customerNameOrEmail')"
          :filterable="true"
          :multiple="true"
          :remote="true"
          :remote-method="getCustomerOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in userList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('inventory.cname')">
        <el-select
          v-model="form.product_id"
          :placeholder="t('common.inputText') + t('inventory.cname')"
          :filterable="true"
          :multiple="true"
          :remote="true"
          :remote-method="getProductOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.cname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('warehouse.name')">
        <el-select
          v-model="form.warehouse_id"
          :placeholder="t('common.inputText') + t('warehouse.name')"
          :filterable="true"
          :multiple="true"
          :remote="true"
          :remote-method="getWarehouseOptions"
          :loading="selectLoading"
          style="width: 250px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('order.orderCode')">
        <el-input
          v-model="form.order_no"
          :clearable="true"
          :placeholder="t('order.orderCode')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('order.theTypeOfOrder')">
        <el-select
          :clearable="true"
          v-model="form.order_type"
          :placeholder="t('order.theTypeOfOrder')"
          style="width: 250px"
        >
          <el-option
            v-for="item in orderTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('inventory.source_table')">
        <el-select
          :clearable="true"
          v-model="form.source"
          :placeholder="t('inventory.source_table')"
          style="width: 250px"
        >
          <el-option
            v-for="item in sourceTableList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 新增 库存类型 搜索 -->
      <el-form-item :label="t('inventory.is_futures')">
        <el-select
          :clearable="true"
          v-model="form.is_futures"
          :placeholder="t('inventory.is_futures')"
          style="width: 250px"
        >
          <el-option
            v-for="item in isFuturesList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.receiptMethod')">
        <el-select
          :clearable="true"
          v-model="form.delivery_method"
          :placeholder="t('order.receiptMethod')"
          style="width: 250px"
        >
          <el-option
            v-for="item in receiptMethodList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.orderStatus')">
        <el-select
          :clearable="true"
          v-model="form.order_status"
          :placeholder="t('order.orderStatus')"
          :multiple="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in orderStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.aftersales_status')">
        <el-select
          :clearable="true"
          v-model="form.aftersales_status"
          :placeholder="t('order.aftersales_status')"
          :multiple="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in afterSalesStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.paymentStatus')">
        <el-select
          :clearable="true"
          v-model="form.pay_status"
          :placeholder="t('order.paymentStatus')"
          :multiple="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in paymentStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.exceptionstatus')">
        <el-select
          :clearable="true"
          v-model="form.exceptionstatus"
          :multiple="true"
          :placeholder="t('order.exceptionstatus')"
          style="width: 250px"
        >
          <el-option
            v-for="item in exceptionStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.leader')">
        <el-select
          :clearable="true"
          v-model="form.owner"
          :placeholder="t('order.leader')"
          filterable
          style="width: 250px"
        >
          <el-option
            v-for="item in leaderList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.collaborators')">
        <el-select
          :clearable="true"
          v-model="form.partner"
          :placeholder="t('order.collaborators')"
          filterable
          style="width: 250px"
        >
          <el-option
            v-for="item in collaboratorsList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('order.creationTime')">
        <el-date-picker
          :clearable="true"
          v-model="form.date"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          @change="changeTime"
          :editable="false"
          unlink-panels
          :class="{ '!w-230px': isMobile }"
        />
      </el-form-item>
      <el-form-item>
        <div class="mobile-button-group horizontal">
          <el-button type="primary" icon="Search" @click="search">{{
            t('common.query')
          }}</el-button>
          <el-button icon="Refresh" @click="reset">{{ t('common.reset') }}</el-button>
        </div>
      </el-form-item>
    </el-form>
    <!--    操作项-->
    <div class="flex flex-items-center my-5">
      <el-button type="primary" @click="handleAdd('add')">
        {{ t('order.add') }}
      </el-button>
    </div>

    <!-- 移动端卡片视图 -->
    <div v-if="isMobile" class="mobile-card">
      <el-card v-for="item in dataList" :key="item.id" class="order-card">
        <template #header>
          <div class="card-header">
            <el-link :underline="false" type="primary" @click="handleJump('detail', item)">
              {{ item.order_no }}
            </el-link>
            {{ useEnumeratePicker(orderStatusList, item.order_status) }}
          </div>
        </template>

        <div class="card-content">
          <div class="info-row">
            <span class="label">{{ t('order.customer') }}:</span>
            <el-link :underline="false" type="primary" @click="handleJump('customer', item)">
              {{ item.user }}
            </el-link>
          </div>

          <div class="info-row">
            <span class="label">id:</span>
            <el-link :underline="false">
              {{ item.id }}
            </el-link>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.paymentStatus') }}:</span>
            {{ useEnumeratePicker(paymentStatusList, item.pay_status) }}
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.orderStatus') }}:</span>
            {{ useEnumeratePicker(orderStatusList, item.order_status) }}
          </div>
          <div class="info-row" v-if="item.aftersales_status">
            <span class="label">{{ t('order.aftersales_status') }}:</span>
            <el-tag
              class="!bg-[var(--el-color-info-light-9)] !border-none !font-600"
              :class="{
                '!text-[#FFA500]': item?.aftersales_status === 1, // 退款审批中
                '!text-[#F85149]': item?.aftersales_status === 2, // 退货退款审批中
                '!text-[#00dc68]': item?.aftersales_status === 3, // 退货中
                '!text-[#67c23a]': item?.aftersales_status === 4, // 已退货
                '!text-[#1E90FF]': item?.aftersales_status === 8, // 退款中
                '!text-[#9370DB]': item?.aftersales_status === 16, // 已退款
                '!text-[#FF6B6B]': item?.aftersales_status === 32 // 已退货 已退款
              }"
            >
              {{ useEnumeratePicker(afterSalesStatusList, item.aftersales_status) }}
            </el-tag>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.buyGoods') }}:</span>
            <div>
              <div v-for="(p, pIndex) in item.buy_goods" :key="pIndex" class="text-right">
                <span v-if="p.warehouse_name">[{{ p.warehouse_name }}]</span>
                <span v-if="p.is_futures">[{{ p.is_futures }}]</span>
                <span v-if="p.code">[{{ p.code }}]</span>
                <span>[{{ p.quantity }}]</span>
                <span v-if="p.wholesal_id">
                  <ElLink type="primary" @Click="handleJump('wholesalDetail', p)">
                    [{{ p.wholesal_id }}]
                  </ElLink>
                </span>
              </div>
            </div>
          </div>

          <div class="info-row">
            <span class="label">{{ t('order.receiptMethod') }}:</span>
            <span class="value">{{
              useEnumeratePicker(receiptMethodList, item.delivery_method)
            }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.country_name') }}:</span>
            <span class="value">{{ item.country_name }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.consignee') }}:</span>
            <span class="value">{{ item.consignee }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.address') }}:</span>
            <span class="value">{{ item.address }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.product_total_original_amount') }}:</span>
            <span class="value">{{ item.product_total_original_amount }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.logistics_fee') }}:</span>
            <span class="value">{{ item.logistics_fee }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.total_amount') }}:</span>
            <span class="value">{{ item.total_amount }}</span>
          </div>

          <div class="info-row">
            <span class="label">{{ t('order.theAmountOfThePayment') }}:</span>
            <span class="value">{{ item.pay_amount }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.paymentType') }}:</span>
            <span class="value">{{ item.pay_method }}</span>
            <span class="value">{{ useEnumeratePicker(paymentTypeList, item.pay_method) }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.currency') }}:</span>
            <span class="value">{{ useEnumeratePicker(currencyList, item.currency) }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('inventory.source_table') }}:</span>
            <span class="value">{{ useEnumeratePicker(sourceTableList, item.source) }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.creator') }}:</span>
            <span class="value">{{ useEnumeratePicker(signatoryList, item.creator) }}</span>
          </div>
          <div class="info-row">
            <span class="label">{{ t('order.create_time') }}:</span>
            <span class="value">{{ item.create_time }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 桌面端表格视图 -->
    <div v-else class="mobile-table">
      <Table
        showAction
        :columns="tableColumns"
        :data="dataList"
        :loading="tableLoading"
        highlight-current-row
        stripe
        border
      />
    </div>

    <!--    分页-->
    <Pagination
      class="mobile-table"
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>
  <!--      上传支付审核弹框-->
  <DialogUpload ref="DialogUploadRef" @refresh="initialize" class="mobile-dialog" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useEnumeratePicker, useEnumerateMultiplePicker } from '@/utils'
import {
  getOrderEnumApi,
  getListApi,
  orderCancelApi,
  orderDeleteApi,
  lockInventoryApi
} from '@/api/order'
import { ElMessage, ElMessageBox } from 'element-plus'
import DialogUpload from '@/views/Order/Order/components/DialogUpload/index.vue'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import { getSelectApi as getCustomerSelectApi } from '@/api/customer'
import { useAppStore } from '@/store/modules/app'
import { Table } from '@/components/Table'
import { useOrderTableColumns } from './components/hooks/useTableColumns'
import { getListApi as getProductListApi } from '@/api/product'
import { getListApi as getWarehouseListApi } from '@/api/warehouse'

const { t } = useI18n()
const { push } = useRouter()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const paginationTotal = ref<number>(0)
const DialogUploadRef = ref<InstanceType<typeof DialogUpload>>()
const selectLoading = ref<boolean>(false)

const form = ref<Record<string, any>>({
  order_category: 'order',
  id: '',
  user_id: '',
  order_no: '',
  order_type: '',
  delivery_method: '',
  order_status: '',
  aftersales_status: '',
  pay_status: '',
  owner: '',
  partner: '',
  date: [],
  start_time: '',
  end_time: '',
  pageIndex: 1,
  pageSize: 30,
  is_futures: ''
})

const orderTypeList = ref<Array<Record<string, any>>>([])
const sourceTableList = ref<Array<Record<string, any>>>([])
const receiptMethodList = ref<Array<Record<string, any>>>([])
const orderStatusList = ref<Array<Record<string, any>>>([])
const paymentStatusList = ref<Array<Record<string, any>>>([])
const leaderList = ref<Array<Record<string, any>>>([])
const collaboratorsList = ref<Array<Record<string, any>>>([])
const currencyList = ref<Array<Record<string, any>>>([])
const paymentTypeList = ref<Array<Record<string, any>>>([])
const userList = ref<Array<Record<string, any>>>([])
const signatoryList = ref<Array<Record<string, any>>>([])
const contractSigningStatusList = ref<Array<Record<string, any>>>([])
const singleOrderMethodList = ref<Array<Record<string, any>>>([])
const payTermsList = ref<Array<Record<string, any>>>([]) // 支付条款
const exceptionStatusList = ref<Array<Record<string, any>>>([])
const isFuturesList = ref<Array<Record<string, any>>>([])
const afterSalesStatusList = ref<Array<Record<string, any>>>([])
// 客户异步下拉框
const getCustomerOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const userResp = await getCustomerSelectApi({ cusname: value })
    userList.value = userResp.data
    selectLoading.value = false
  }
}

// 产品异步下拉框
const productList = ref<Array<Record<string, any>>>([])
const getProductOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const productResp = await getProductListApi({ cname: value })
    productList.value = productResp.data.list
    console.log(666, productList.value)
    selectLoading.value = false
  }
}

//仓库异步下拉框
const warehouseList = ref<Array<Record<string, any>>>([])
const getWarehouseOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const warehouseResp = await getWarehouseListApi({ name: value })
    warehouseList.value = warehouseResp.data.list
    console.log(666, warehouseList.value)
    selectLoading.value = false
  }
}
//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}

//点击跳转到新增
const handleAdd = (type: string) => {
  push({ path: `/order/order-management/${type}` })
}

/**
 * 取消订单
 * @param row
 */
const handleCancelOrder = (row: Record<string, any>) => {
  ElMessageBox.confirm(`是否确认取消订单？`, t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await orderCancelApi(row.id)
      ElMessage.success('订单已取消成功')
      await initialize()
    })
    .catch(() => {})
}
/**
 * 删除订单
 * @param row
 */
const handleDeleteOrder = (row: Record<string, any>) => {
  ElMessageBox.confirm(`是否确认删除订单？`, t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await orderDeleteApi(row.id)
      ElMessage.success('订单删除成功')
      await initialize()
    })
    .catch(() => {})
}
//跳转
const handleJump = (type: string, row: Record<string, any>) => {
  const path = ref<string>('') // 默认值为空字符串
  const query = reactive<{ [key: string]: string }>({}) // 默认值为空字符串
  switch (type) {
    case 'customer':
      path.value = `/customer/customerList/detail`
      query.id = row.user_id
      query.source = `/order/order-management`
      break
    case 'lockInventory':
      handleLockInventory(row)
      break
    case 'wholesalDetail':
      path.value = `/order/wholesal-order-management/detail`
      query.id = row.wholesal_id
      break
    default:
      path.value = `/order/order-management/${type}`
      query.id = row.id
      break
  }

  push({ path: path.value, query })
}

const handleLockInventory = (row: Record<string, any> | undefined) => {
  console.log(row)
  ElMessageBox.confirm(`是否确认锁定库存？`, t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await lockInventoryApi({ id: row?.id })
      ElMessage.success('锁定库存成功')
      await initialize()
    })
    .catch(() => {})
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getOrderEnumApi({ field: 'all' })
  orderTypeList.value = resp.data.order_type
  sourceTableList.value = resp.data.source
  receiptMethodList.value = resp.data.delivery_method
  currencyList.value = resp.data.currency
  orderStatusList.value = resp.data.status
  paymentStatusList.value = resp.data.pay_status
  leaderList.value = resp.data.operator
  collaboratorsList.value = resp.data.operator
  paymentTypeList.value = resp.data.pay_method
  contractSigningStatusList.value = resp.data.contract_signing_status
  singleOrderMethodList.value = resp.data.single_order_method
  payTermsList.value = resp.data.pay_terms
  exceptionStatusList.value = resp.data.exceptionstatus
  isFuturesList.value = resp.data.is_futures || []
  afterSalesStatusList.value = resp.data.aftersales_status || []

  const signatoryResp = await getOperatorSelectListApi({})
  signatoryList.value = signatoryResp.data.list
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}
const search = () => {
  form.value.pageIndex = 1
  initialize()
}
//重置查询项
const reset = () => {
  form.value = {
    order_category: 'order',
    user_id: '',
    order_no: '',
    order_type: '',
    delivery_method: '',
    order_status: '',
    aftersales_status: '',
    pay_status: '',
    owner: '',
    partner: '',
    date: [],
    start_time: '',
    end_time: '',
    pageIndex: 1,
    pageSize: 30,
    is_futures: ''
  }
  paginationTotal.value = 0
  initialize()
}

onActivated(() => {
  getDropDownBoxInfo()
  initialize()
})

const tableColumns = useOrderTableColumns(
  handleJump,
  useEnumeratePicker,
  useEnumerateMultiplePicker,
  paymentStatusList,
  orderStatusList,
  orderTypeList,
  sourceTableList,
  receiptMethodList,
  signatoryList,
  contractSigningStatusList,
  singleOrderMethodList,
  payTermsList,
  paymentTypeList,
  currencyList,
  exceptionStatusList,
  afterSalesStatusList
)
</script>

<style lang="less" scoped>
:deep(.el-table--default .el-table__cell) {
  padding: 2px 0 !important;
}

:deep(.el-table--default .cell) {
  padding: 0 4px;
}

:deep(.el-form-item__label) {
  min-width: 68px;
}
</style>
